package com.pj.compose.ui.compose

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.pj.compose.R

val appBarHeight = 50
const val titleTop = 8
const val iconTop = 10


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommonTopBar(
    title: String,
    useBack: Boolean = true,
    backClick: () -> Unit = {},
    actions: @Composable RowScope.() -> Unit = {},
) {
    val density = LocalDensity.current
    val statusBarHeight = with(density) {
        WindowInsets.statusBars.getTop(this).toDp()
    }
    CenterAlignedTopAppBar(
        title = { Text(text = title, Modifier.padding(top = titleTop.dp), fontSize = 20.sp) },
        modifier = Modifier
            .height((appBarHeight + statusBarHeight.value).dp),
        navigationIcon = {
            if (useBack)
                Icon(
                    painter = painterResource(id = R.drawable.ic_arrow_back_white),
                    contentDescription = "Back",
                    Modifier
                        .padding(top = iconTop.dp)
                        .clickable(enabled = true, onClick = backClick),
                    tint = Color.White
                )
        },
        actions = {
            Row(
                Modifier.padding(top = iconTop.dp)
            ) { actions() }
        },
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
            containerColor = MaterialTheme.colorScheme.primary, titleContentColor = Color.White
        ),
    )
}

@Composable
fun AppTopBarColumn(
    title: String,
    modifier: Modifier = Modifier,
    backClick: () -> Unit,
    actions: @Composable RowScope.() -> Unit = {},
    content: @Composable ColumnScope.() -> Unit
) {
    Column(modifier = modifier) {
//        Box(modifier = Modifier.windowInsetsPadding(WindowInsets.systemBars.only(WindowInsetsSides.Top)))
        CommonTopBar(title = title, backClick = backClick, actions = actions)
        Column(content = content)
    }
}


@Preview
@Composable
private fun CommonTopBarPreview() {
    CommonTopBar(title = "标题", backClick = {}) {
        Icon(
            imageVector = Icons.Default.Add, contentDescription = "Add", tint = Color.White
        )
    }
}